package com.kly.job;

import com.kly.model.domain.User;
import com.kly.service.UserService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author admin
 * @date 2025/2/21
 */
// @Component
public class InsertUsersTask {

    @Resource
    private UserService userService;

    public static final int BATCH_SIZE = 10;

    @Scheduled(fixedRate = Long.MAX_VALUE, initialDelay = 2000)
    public void insertUsers() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // List<User> users = new ArrayList<>();
        List<CompletableFuture<Void>> futureList = new ArrayList<>();
        int j = 0;
        for (int i = 0; i < BATCH_SIZE; i++) {
            List<User> users = new ArrayList<>();
            while(true) {
                j++;
                User user = new User();
                user.setAccount("account" + i);
                user.setUsername("username" + i);
                user.setAvatarUrl("https://p5.img.cctvpic.com/photoworkspace/contentimg/2023/03/30/2023033011303020756.jpg");
                user.setGender(1);
                user.setPassword("12345678");
                user.setPhone(i + "123");
                user.setEmail(i + "@qq.com");
                user.setStatus(1);
                user.setCreateTime(new Date());
                user.setIsDelete(0);
                user.setTags("[]");
                user.setProfile("简介" + i);
                user.setPlanetCode(i + 10 + "");

                users.add(user);
                if(j % 100 == 0) {
                    break;
                }
            }

            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                userService.saveBatch(users, 10);
            });

            futureList.add(future);
        }

        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[]{})).join();

        stopWatch.stop();
        System.out.println("插入" + BATCH_SIZE + "条数据耗时：" + stopWatch.getTotalTimeMillis() + "ms");
    }
}
